{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "fb288042",
   "metadata": {},
   "source": [
    "# Weight Packing"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "aa75e811",
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "feef80ed",
   "metadata": {},
   "outputs": [],
   "source": [
    "def pack_weights(uint8tensor, bits):\n",
    "    if uint8tensor.shape[0] * bits % 8 != 0:\n",
    "        raise ValueError(\"The total number of bits must be a multiple of 8.\")\n",
    "\n",
    "    num_values = uint8tensor.shape[0] * bits // 8\n",
    "    num_steps = 8 // bits\n",
    "    unpacked_idx = 0\n",
    "    packed_tensor = torch.zeros(num_values, dtype=torch.uint8)\n",
    "    for i in range(num_values):\n",
    "        for j in range(num_steps):\n",
    "            packed_tensor[i] |= (uint8tensor[unpacked_idx] & 0xFF) << (j * bits)\n",
    "            unpacked_idx += 1\n",
    "    return packed_tensor\n",
    "\n",
    "\n",
    "def unpack_weights(uint8tensor, bits):\n",
    "    num_values = uint8tensor.shape[0] * 8 // bits\n",
    "    num_steps = 8 // bits\n",
    "    unpacked_idx = 0\n",
    "    unpacked_tensor = torch.zeros(num_values, dtype=torch.uint8)\n",
    "    mask = (1 << bits) - 1\n",
    "    for i in range(uint8tensor.shape[0]):\n",
    "        for j in range(num_steps):\n",
    "            unpacked_tensor[unpacked_idx] = mask & (uint8tensor[i] >> (j * bits))\n",
    "            unpacked_idx += 1\n",
    "    return unpacked_tensor"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "11d1a6cd",
   "metadata": {},
   "outputs": [],
   "source": [
    "unpacked_tensor = torch.tensor([1, 0, 3, 2, 3, 1, 2, 3], dtype=torch.uint8)\n",
    "packed_tensor = pack_weights(unpacked_tensor, 2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "995f3f8e",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([1, 0, 3, 2, 3, 1, 2, 3], dtype=torch.uint8)"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "unpack_weights(packed_tensor, 2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0fb123a5",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "pytorch-cu128",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.13"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
